package com.china08.yxyapi.api.manage.edu.platform.continuedu.renwu;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.china08.yxyapi.api.YxyApiBaseController;
import com.china08.yxyapi.entity.db.continuedu.YxyContinueduLesson;
import com.china08.yxyapi.entity.db.continuedu.YxyContinueduTaskLesson;
import com.china08.yxyapi.model.YxyApiReqModel;
import com.china08.yxyapi.repository.db.continuedu.YxyContinueduLessonRepository;
import com.china08.yxyapi.repository.db.continuedu.YxyContinueduTaskLessonRepository;

import io.swagger.annotations.ApiOperation;

@CrossOrigin
@RestController
public class YxyContinueduRenWuAddLessonController extends YxyApiBaseController {

    @Autowired
    YxyContinueduLessonRepository lessonRepository;

    @Autowired
    YxyContinueduTaskLessonRepository taskLessonRepository;

    @ApiOperation(value = "")
    @RequestMapping(value = "/api_yw/manage/edu/platform/continuedu/renwu/add/lesson", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public void precess(HttpServletRequest request, HttpServletResponse response, @RequestBody ReqModel reqModel) {
        String taskId = reqModel.taskId;
        List<String> lessonIds = reqModel.lessonIds;

        Set<String> ids = new HashSet<>();
        for (String id : lessonIds) {
            ids.add(id);
        }

        YxyContinueduTaskLesson taskLesson = taskLessonRepository.findTop1ByTaskIdOrderByOrderNumDesc(taskId);
        Integer orderNum = 1;
        if (taskLesson != null) {
            orderNum = taskLesson.getOrderNum() + 1;
        }

        for (String id : ids) {
            taskLesson = new YxyContinueduTaskLesson();
            YxyContinueduLesson lesson = lessonRepository.findById(id);
            if (lesson != null) {
                taskLesson.setTaskId(taskId);
                taskLesson.setLessonId(id);
                taskLesson.setLessonName(lesson.getName());
                taskLesson.setOrderNum(orderNum);
            }
            taskLessonRepository.save(taskLesson);
            orderNum++;
        }

    }

    public static class ReqModel extends YxyApiReqModel {
        public String taskId;
        public List<String> lessonIds;

        @Override
        public void autoCheck() {
        }
    }

}
